<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\common\enum\SettingEnum;
use app\common\model\SettingModel;
use app\common\service\SettingService;
use think\facade\Cache;
use think\response\Json;

class Setting extends AdminBaseController
{
    public function get($key = null): Json
    {
        $SettingService = new SettingService;
        if ($key == null) {
            $data = $SettingService::getAll();
        } else {
            $data = [
                $key => $SettingService::getItem($key)
            ];
        }
        return json(render_array_success($data));
    }

    public function save()
    {
        $data = $this->request->only(['key', 'value_data']);

        // 数据验证
        $rule = [
            'key' => 'require|in:' . implode(',', array_keys(SettingEnum::data())),
            'value_data' => 'require',
        ];
        validate($rule)->check($data);

        $SettingService = new SettingService;
        $res = $SettingService::update($data['key'], $data['value_data']);

        return json($res);
    }
}
